package com.syn.synold4s.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;

import com.gaoyi.basemodule.baseUtil.LanguageUtils;
import com.gaoyi.basemodule.baseconstant.SPName;
import com.syn.synold4s.R;
import com.syn.synold4s.util.NotificationUtil;

public class CloseService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String projCode = intent.getStringExtra(SPName.PROJ_CODE);
        String mapLang = intent.getStringExtra(SPName.MAP_TYPE);
        Intent startSignalR = new Intent(this, MqttService.class);
        startSignalR.putExtra(SPName.PROJ_CODE, projCode);
        startSignalR.putExtra(SPName.MAP_TYPE, mapLang);
        startService(startSignalR);
        showNotification(mapLang==null?"":mapLang);
        return START_STICKY;
    }

    /**
     * 发送後台通知
     */
    @SuppressLint("ForegroundServiceType")
    private void showNotification(String mapLang) {
        boolean isEnglish = mapLang.equals(LanguageUtils.MAP_LANG_ENGLISH);
        String title = isEnglish ? "Background Service" : "後台服務";
        String content = isEnglish ? "Avoid not receiving alert notifications" : "避免無法接收警報通知";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationUtil.getInstance().getNotificationManager().createNotificationChannel(NotificationUtil.getInstance().getForegroundChannel());
            Notification.Builder builder = NotificationUtil.getInstance().getForegroundNotification(this)
                    .setAutoCancel(true)
                    .setContentTitle(title)
                    .setContentText(content)
                    .setSmallIcon(R.drawable.notify_icon);
            startForeground(1000001, builder.build());
        } else {
            NotificationCompat.Builder builder = NotificationUtil.getInstance().getForegroundNotificationCompat(this)
                    .setAutoCancel(true)
                    .setContentTitle(title)
                    .setContentText(content)
                    .setColor(ContextCompat.getColor(this, R.color.color_main))
                    .setSmallIcon(R.drawable.notify_icon);
            startForeground(1000001, builder.build());
        }
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("TAG", "closeService onDestroy");
//        取消显示通知
        stopForeground(true);
        MqttService.stopMqtt();
        stopService(new Intent(this, MqttService.class));
    }
}
